<template>
  <div class="stats-page">
    <el-page-header>
      <template slot="content">
        <h1>统计信息</h1>
        <p>查看平台各项数据指标和趋势分析</p>
      </template>
    </el-page-header>
    
    <!-- 时间范围选择器 -->
    <div class="time-filter-container">
      <el-radio-group v-model="timeRange" @change="loadStats">
        <el-radio-button label="day">今日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="year">今年</el-radio-button>
        <el-radio-button label="all">全部时间</el-radio-button>
      </el-radio-group>
      
      <el-date-picker
        v-model="customTimeRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="margin-left: 20px;"
        @change="handleCustomTimeRange"
      />
      
      <el-button type="primary" @click="loadStats" style="margin-left: 16px;">
        <i class="el-icon-refresh"></i> 刷新数据
      </el-button>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-loading-spinner />
    </div>
    
    <div v-else>
      <!-- 概览卡片 -->
      <div class="overview-cards">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon download-icon">
              <i class="el-icon-download"></i>
            </div>
            <div class="card-info">
              <div class="card-title">总下载量</div>
              <div class="card-value">{{ formatNumber(stats.totalDownloads || 0) }}</div>
              <div class="card-change" :class="getChangeClass(stats.downloadChange)">
                <i :class="getChangeIcon(stats.downloadChange)"></i>
                {{ Math.abs(stats.downloadChange || 0) }}% vs 上期
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon package-icon">
              <i class="el-icon-collection-tag"></i>
            </div>
            <div class="card-info">
              <div class="card-title">包数量</div>
              <div class="card-value">{{ formatNumber(stats.totalPackages || 0) }}</div>
              <div class="card-change" :class="getChangeClass(stats.packageChange)">
                <i :class="getChangeIcon(stats.packageChange)"></i>
                {{ Math.abs(stats.packageChange || 0) }}% vs 上期
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon tag-icon">
              <i class="el-icon-price-tag"></i>
            </div>
            <div class="card-info">
              <div class="card-title">标签数量</div>
              <div class="card-value">{{ formatNumber(stats.totalTags || 0) }}</div>
              <div class="card-change" :class="getChangeClass(stats.tagChange)">
                <i :class="getChangeIcon(stats.tagChange)"></i>
                {{ Math.abs(stats.tagChange || 0) }}% vs 上期
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon discussion-icon">
              <i class="el-icon-chat-dot-round"></i>
            </div>
            <div class="card-info">
              <div class="card-title">讨论数量</div>
              <div class="card-value">{{ formatNumber(stats.totalDiscussions || 0) }}</div>
              <div class="card-change" :class="getChangeClass(stats.discussionChange)">
                <i :class="getChangeIcon(stats.discussionChange)"></i>
                {{ Math.abs(stats.discussionChange || 0) }}% vs 上期
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 图表区域 -->
      <div class="charts-container">
        <!-- 下载趋势图 -->
        <el-card class="chart-card">
          <template slot="header">
            <div class="card-header">
              <span>下载趋势</span>
            </div>
          </template>
          <div class="chart-content">
            <div id="downloadTrendChart" class="chart"></div>
          </div>
        </el-card>
        
        <!-- 热门包排名 -->
        <el-card class="chart-card">
          <template slot="header">
            <div class="card-header">
              <span>热门包下载排名</span>
            </div>
          </template>
          <div class="chart-content">
            <div id="topPackagesChart" class="chart"></div>
          </div>
        </el-card>
      </div>
      
      <!-- 标签和讨论统计 -->
      <div class="stats-grid">
        <!-- 标签使用分布 -->
        <el-card class="stat-card">
          <template slot="header">
            <div class="card-header">
              <span>标签使用分布</span>
            </div>
          </template>
          <div class="stat-content">
            <div id="tagDistributionChart" class="chart"></div>
          </div>
        </el-card>
        
        <!-- 讨论活跃度 -->
        <el-card class="stat-card">
          <template slot="header">
            <div class="card-header">
              <span>讨论活跃度</span>
            </div>
          </template>
          <div class="stat-content">
            <div id="discussionActivityChart" class="chart"></div>
          </div>
        </el-card>
      </div>
      
      <!-- 详细数据表格 -->
      <el-card class="data-table-card">
        <template slot="header">
          <div class="card-header">
            <span>详细下载统计</span>
          </div>
        </template>
        <el-table 
          :data="downloadDetails"
          style="width: 100%"
        >
          <el-table-column prop="date" label="日期" width="150" />
          <el-table-column prop="downloads" label="下载量" width="120" align="right">
            <template slot-scope="scope">
              {{ formatNumber(scope.row.downloads) }}
            </template>
          </el-table-column>
          <el-table-column prop="uniqueVisitors" label="独立访问" width="120" align="right">
            <template slot-scope="scope">
              {{ formatNumber(scope.row.uniqueVisitors || 0) }}
            </template>
          </el-table-column>
          <el-table-column prop="avgDownloadsPerPackage" label="包均下载" width="120" align="right">
            <template slot-scope="scope">
              {{ (scope.row.avgDownloadsPerPackage || 0).toFixed(1) }}
            </template>
          </el-table-column>
          <el-table-column label="趋势" width="150">
            <template slot-scope="scope">
              <div class="trend-indicator" :class="getTrendClass(scope.row.trend)">
                <i :class="getTrendIcon(scope.row.trend)"></i>
                <span>{{ scope.row.trend || 0 }}%</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'StatsPage',
  layout: 'default',
  data() {
    return {
      loading: false,
      timeRange: 'month', // day, week, month, year, all
      customTimeRange: null,
      
      // 统计数据
      stats: {
        totalDownloads: 0,
        totalPackages: 0,
        totalTags: 0,
        totalDiscussions: 0,
        downloadChange: 0,
        packageChange: 0,
        tagChange: 0,
        discussionChange: 0
      },
      
      // 下载趋势数据
      downloadTrendData: [],
      
      // 热门包数据
      topPackages: [],
      
      // 标签分布数据
      tagDistribution: [],
      
      // 讨论活跃度数据
      discussionActivityData: [],
      
      // 详细下载统计
      downloadDetails: [],
      
      // 图表实例
      charts: {}
    }
  },
  async fetch() {
    await this.loadStats()
  },
  mounted() {
    // 在组件挂载后初始化图表
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  beforeDestroy() {
    // 组件销毁前销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart && typeof chart.dispose === 'function') {
        chart.dispose()
      }
    })
  },
  methods: {
    async loadStats() {
      this.loading = true
      try {
        // 构建请求参数
        const params = {
          timeRange: this.timeRange
        }
        
        if (this.customTimeRange && this.customTimeRange.length === 2) {
          params.startDate = this.customTimeRange[0]
          params.endDate = this.customTimeRange[1]
        }
        
        // 加载总体统计数据
        const statsResponse = await this.$axios.get('/stats/overview', { params })
        this.stats = statsResponse
        
        // 加载下载趋势数据
        const trendResponse = await this.$axios.get('/stats/download-trend', { params })
        this.downloadTrendData = trendResponse
        
        // 加载热门包数据
        const packagesResponse = await this.$axios.get('/stats/top-packages', { params })
        this.topPackages = packagesResponse
        
        // 加载标签分布数据
        const tagsResponse = await this.$axios.get('/stats/tag-distribution', { params })
        this.tagDistribution = tagsResponse
        
        // 加载讨论活跃度数据
        const discussionsResponse = await this.$axios.get('/stats/discussion-activity', { params })
        this.discussionActivityData = discussionsResponse
        
        // 加载详细下载统计
        const detailsResponse = await this.$axios.get('/stats/download-details', { params })
        this.downloadDetails = detailsResponse
        
        // 更新图表
        this.updateCharts()
      } catch (error) {
        this.$message.error('加载统计数据失败：' + error.message)
        // 设置模拟数据
        this.setMockData()
      } finally {
        this.loading = false
      }
    },
    
    handleCustomTimeRange() {
      if (this.customTimeRange && this.customTimeRange.length === 2) {
        this.timeRange = 'custom'
        this.loadStats()
      }
    },
    
    setMockData() {
      // 模拟统计数据
      this.stats = {
        totalDownloads: 125348,
        totalPackages: 486,
        totalTags: 128,
        totalDiscussions: 324,
        downloadChange: 12.5,
        packageChange: 8.2,
        tagChange: 5.7,
        discussionChange: 15.3
      }
      
      // 模拟下载趋势数据
      const dates = []
      const downloads = []
      const now = new Date()
      
      for (let i = 29; i >= 0; i--) {
        const date = new Date(now)
        date.setDate(date.getDate() - i)
        dates.push(date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }))
        downloads.push(Math.floor(Math.random() * 3000) + 1000)
      }
      
      this.downloadTrendData = {
        dates,
        downloads
      }
      
      // 模拟热门包数据
      const packageNames = ['vue', 'react', 'express', 'lodash', 'moment', 'axios', 'jquery', 'popper.js', 'chart.js', 'bootstrap']
      this.topPackages = packageNames.map(name => ({
        name,
        downloads: Math.floor(Math.random() * 50000) + 10000
      })).sort((a, b) => b.downloads - a.downloads).slice(0, 10)
      
      // 模拟标签分布数据
      const tagNames = ['frontend', 'backend', 'database', 'utility', 'ui', 'testing', 'security', 'performance', 'devops']
      this.tagDistribution = tagNames.map(name => ({
        name,
        value: Math.floor(Math.random() * 100) + 20
      }))
      
      // 模拟讨论活跃度数据
      this.discussionActivityData = {
        dates: dates.slice(-7),
        discussions: dates.slice(-7).map(() => Math.floor(Math.random() * 20) + 5),
        comments: dates.slice(-7).map(() => Math.floor(Math.random() * 100) + 20)
      }
      
      // 模拟详细下载统计
      this.downloadDetails = dates.slice(-10).map((date, index) => ({
        date,
        downloads: downloads.slice(-10)[index],
        uniqueVisitors: Math.floor(downloads.slice(-10)[index] * 0.7),
        avgDownloadsPerPackage: Math.floor(downloads.slice(-10)[index] / this.stats.totalPackages),
        trend: Math.floor(Math.random() * 30) - 10
      }))
    },
    
    initCharts() {
      // 初始化下载趋势图
      this.charts.downloadTrend = echarts.init(document.getElementById('downloadTrendChart'))
      
      // 初始化热门包排名图
      this.charts.topPackages = echarts.init(document.getElementById('topPackagesChart'))
      
      // 初始化标签分布图
      this.charts.tagDistribution = echarts.init(document.getElementById('tagDistributionChart'))
      
      // 初始化讨论活跃度图
      this.charts.discussionActivity = echarts.init(document.getElementById('discussionActivityChart'))
      
      // 监听窗口大小变化，重新调整图表大小
      window.addEventListener('resize', this.handleResize)
    },
    
    updateCharts() {
      // 更新下载趋势图
      this.updateDownloadTrendChart()
      
      // 更新热门包排名图
      this.updateTopPackagesChart()
      
      // 更新标签分布图
      this.updateTagDistributionChart()
      
      // 更新讨论活跃度图
      this.updateDiscussionActivityChart()
    },
    
    updateDownloadTrendChart() {
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>下载量: {c}次'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.downloadTrendData.dates || [],
          axisLabel: {
            interval: Math.floor((this.downloadTrendData.dates?.length || 1) / 10),
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [{
          name: '下载量',
          type: 'line',
          smooth: true,
          data: this.downloadTrendData.downloads || [],
          itemStyle: {
            color: '#1890ff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(24, 144, 255, 0.3)'
            }, {
              offset: 1,
              color: 'rgba(24, 144, 255, 0.05)'
            }])
          }
        }]
      }
      
      this.charts.downloadTrend.setOption(option)
    },
    
    updateTopPackagesChart() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}<br/>下载量: {c}次'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        yAxis: {
          type: 'category',
          data: this.topPackages.map(item => item.name).reverse(),
          axisLabel: {
            interval: 0
          }
        },
        series: [{
          name: '下载量',
          type: 'bar',
          data: this.topPackages.map(item => item.downloads).reverse(),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
              offset: 0,
              color: '#1890ff'
            }, {
              offset: 1,
              color: '#73c0de'
            }])
          }
        }]
      }
      
      this.charts.topPackages.setOption(option)
    },
    
    updateTagDistributionChart() {
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 'center',
          textStyle: {
            fontSize: 12
          },
          formatter: function(name) {
            const item = this.topTags.find(tag => tag.name === name)
            return name + ': ' + item?.value
          }
        },
        series: [{
          name: '标签使用',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: this.tagDistribution
        }]
      }
      
      // 存储前N个标签用于图例显示
      this.topTags = this.tagDistribution.slice(0, 6)
      
      this.charts.tagDistribution.setOption(option)
    },
    
    updateDiscussionActivityChart() {
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['讨论数', '评论数'],
          top: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.discussionActivityData.dates || []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '讨论数',
            type: 'line',
            data: this.discussionActivityData.discussions || [],
            itemStyle: {
              color: '#52c41a'
            }
          },
          {
            name: '评论数',
            type: 'line',
            data: this.discussionActivityData.comments || [],
            itemStyle: {
              color: '#faad14'
            }
          }
        ]
      }
      
      this.charts.discussionActivity.setOption(option)
    },
    
    handleResize() {
      // 重新调整所有图表大小
      Object.values(this.charts).forEach(chart => {
        if (chart && typeof chart.resize === 'function') {
          chart.resize()
        }
      })
    },
    
    formatNumber(num) {
      if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M'
      } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K'
      }
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    
    getChangeClass(change) {
      if (!change) return ''
      return change > 0 ? 'positive' : 'negative'
    },
    
    getChangeIcon(change) {
      if (!change) return 'el-icon-minus'
      return change > 0 ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
    },
    
    getTrendClass(trend) {
      if (trend > 0) return 'trend-up'
      if (trend < 0) return 'trend-down'
      return 'trend-neutral'
    },
    
    getTrendIcon(trend) {
      if (trend > 0) return 'el-icon-arrow-up'
      if (trend < 0) return 'el-icon-arrow-down'
      return 'el-icon-minus'
    }
  },
  computed: {
    // 计算属性可以在这里添加
  }
}
</script>

<style scoped>
.stats-page {
  padding: 24px;
}

.time-filter-container {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 6px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

/* 概览卡片样式 */
.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.overview-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  margin-right: 16px;
}

.download-icon {
  background-color: #e6f7ff;
  color: #1890ff;
}

.package-icon {
  background-color: #f6ffed;
  color: #52c41a;
}

.tag-icon {
  background-color: #fff7e6;
  color: #faad14;
}

.discussion-icon {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #8c8c8c;
  margin-bottom: 4px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 4px;
}

.card-change {
  font-size: 12px;
}

.card-change.positive {
  color: #52c41a;
}

.card-change.negative {
  color: #ff4d4f;
}

/* 图表容器样式 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.chart-card,
.stat-card {
  height: 400px;
}

.chart-content,
.stat-content {
  height: calc(100% - 56px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart {
  width: 100%;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 数据表格样式 */
.data-table-card {
  margin-bottom: 24px;
}

.trend-indicator {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.trend-up {
  background-color: #f6ffed;
  color: #52c41a;
}

.trend-down {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.trend-neutral {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-page {
    padding: 16px;
  }
  
  .time-filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .overview-cards {
    grid-template-columns: 1fr;
  }
  
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .chart-card,
  .stat-card {
    height: 300px;
  }
}
</style>